from django import http
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

from utils.response_code import RETCODE
from . import constants

class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        """
        :param request: 请求对象
        :param uuid: 唯一标识图形验证码所属于的用户
        :return: image/jpg
        """
        # 生成图片验证码
        from libs.captcha.captcha import captcha
        text, image = captcha.generate_captcha()

        # 保存图片验证码
        redis_client = get_redis_connection('verify_image_code')

        redis_client.setex('img_%s' % uuid, constants.IMAGE_CODE_REDIS_EXPIRES, text)

        # 响应图片验证码
        return http.HttpResponse(image, content_type='image/jpeg')

class SmsCodeView(View):
    def get(self, request, mobile):
        # *   1.接收 3个 mobile; 图片验证码img_code; uuid==image_code_id
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        # *   2.验证码 img_code和redis存储的验证码 是否一致 (1.redis取出来(4步) 2.判断是否相等 3.redis img_code 删除)
        # 2.1 链接redis
        img_redis_client = get_redis_connection('verify_image_code')
        # 2.2 取出来  key = uuid
        redis_img_code = img_redis_client.get('img_%s' % uuid)

        if redis_img_code is None:
            return http.JsonResponse({'code': "4001", 'errmsg': '验证码时效了'})
        # 2.3 判断
        # m 千万注意 redis取出来类型 是 Bytes.decode()
        if image_code.lower() != redis_img_code.decode().lower():
            return http.JsonResponse({'code': "4001", 'errmsg': '输入图形验证码有误'})

        # 2.4 删除 redis里面 image_code
        img_redis_client.delete('img_%s' % uuid)

        # *   3.生成随机 6位 短信验证码内容 random.randit()
        from random import randint
        sms_code = "%06d" % randint(0, 999999)

        # *   4.存储 随机6位 redis里面(3步 )
        sms_redis_client = get_redis_connection('sms_code')
        sms_redis_client.setex("sms_%s" % mobile, constants.IMAGE_CODE_REDIS_EXPIRES, sms_code)

        # 1.从redis中取出 避免频繁发送短信的 标识
        send_flag = sms_redis_client.get('send_flag_%s' % mobile)

        # 2.判断 如果标识存在, 不能再次发送
        if send_flag:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '发送短信过于频繁'})

        # 3.如果不存在, 短信发送.标识倒计时再次开启
        p1 = sms_redis_client.pipeline()
        p1.setex("send_flag_%s" % mobile, 60, 1)
        p1.setex("sms_%s" % mobile, constants.IMAGE_CODE_REDIS_EXPIRES, sms_code)
        p1.execute()

        # *   5.发短信---第三方容联云--
        from libs.yuntongxun.sms import CCP
        # 手机号,[验证码,过期时间],短信模板1
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        # CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_EXPIRES], 1)


        from celery_tasks.sms.tasks import cpp_send_sms_code
        cpp_send_sms_code.delay(mobile, sms_code)


        print("短信验证码是:", sms_code)

        # *   6.返回响应对象
        return http.JsonResponse({'code': '0', 'errmsg': '发送短信成功'})

